import { Component } from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Form, Icon, Input, Button, Alert } from 'antd';
import styles from './Login.css';
import auth from 'utils/auth';
import { routerRedux } from 'dva/router';

const FormItem = Form.Item;

function getPrefixIcon(icon) {
  const props = {
    style: {
      fontSize: 13,
    },
  };

  return <Icon type={icon} {...props} />;
}

class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      errorMessage: null,
      inFlight: false,
    };
  }

  redirectToIndex = () => {
    const { dispatch } = this.props;

    dispatch({
      type: 'users/fetchSelfProfile',
    }).then(({ code, msg }) => {
      if (!code) {
        dispatch(routerRedux.push('/'));
      } else {
        this.setState({
          errorMessage: msg,
        });
      }
    });

    this.setState({
      inFlight: false,
    });
  };

  handleSubmitFail = error => {
    this.setState({
      errorMessage: error.message,
      inFlight: false,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      errorMessage: null,
    });

    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          inFlight: true,
        });
        auth
          .login(values.mobile, values.password, values.nonce)
          .then(this.redirectToIndex)
          .catch(this.handleSubmitFail);
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { errorMessage } = this.state;

    return (
      <div className={styles.loginPage}>
        <div className={styles.loginFormWrapper}>
          {errorMessage && (
            <Alert
              message={errorMessage}
              type="error"
              showIcon={true}
              className={styles.errorAlert}
            />
          )}
          <Form onSubmit={this.handleSubmit}>
            <FormItem>
              {getFieldDecorator('mobile', {
                rules: [{ required: true, message: '请输入手机号！' }],
              })(<Input prefix={getPrefixIcon('user')} placeholder="手机号" />)}
            </FormItem>
            <FormItem>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入密码！' }],
              })(<Input prefix={getPrefixIcon('lock')} type="password" placeholder="密码" />)}
            </FormItem>
            <FormItem>
              {getFieldDecorator('nonce', {
                rules: [{ required: true, message: '请输入身份认证码！' }],
              })(<Input prefix={getPrefixIcon('solution')} type="text" placeholder="认证码" />)}
            </FormItem>
            <FormItem>
              <Button
                loading={this.state.inFlight}
                type="primary"
                htmlType="submit"
                className={styles.loginFormButton}>
                登录
              </Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}

if (process.env.UMI_ENV !== 'prod') {
  Login.propTypes = {
    dispatch: PropTypes.func.isRequired,
    form: PropTypes.object.isRequired,
  };
}

Login.defaultProps = {
  form: {},
};

export default connect()(Form.create()(Login));
